package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.BdmOrder;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;

public class WxSendCoodUtils {


    public static String getAccessToken(String appid, String secret) {
        // log.info("initAccessToken:开始运行...");
        String accessToken = null;
        //获取tokcen接口
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appid+"&secret="+secret;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = com.alibaba.fastjson2.JSONObject.parseObject(message);
            accessToken = demoJson.getString("access_token");

            //log.info("返回accessToken:"+accessToken);
            //log.info("initAccessToken:运行结束...");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return accessToken;

    }


    public static void sendGood(String tokenParam, BdmOrder bdmOrder, String openId) throws Exception {
        //  String token=getAccessToken("wx8ee7c46e3f57fa80","4881a7e85282e0238074cde855e16f1f");
        //  System.out.println(token);
        String token=tokenParam;
        String mchId="798633418";
        // String transid="4200002823202508208786276655";
        String outTradeNo =bdmOrder.getNativeId();
        String accessToken=token;
        String openid=openId;
        String desc=bdmOrder.getGoodNames();
        String expressCompany=bdmOrder.getLId();
        String trackingNo=bdmOrder.getLcId();
//        uploadShippingInfo(mchId,outTradeNo,accessToken,openid,desc,expressCompany,trackingNo);

        JSONObject jsonObject = queryWxExpress(token, "YTO", "YT7569148832606");
        //  subOpenId     nativeId  outTradeNo  object.getString("subOpenId")
        // uploadShippingInfo(mchId,outTradeNo,accessToken,openid,desc,expressCompany,trackingNo);
    }

    public static void main(String[] args) throws Exception {
        String token = getAccessToken("wx8ee7c46e3f57fa80", "4881a7e85282e0238074cde855e16f1f");
//        JSONObject jsonObject = queryWxExpress(token, "YTO", "YT7569148832606");
        JSONObject jsonObject = searchWxID("BDM202509101433224692b48c");
        String mchId="798633418";
        String outTradeNo = "4200002822202508141759779471";
        String openid = "ofLFW7D_qQTYt5vqp15oiCFvEgZQ";
        String desc = "本维美超模饮月套餐";
        String expressCompany = "STO";
        String trackingNo = "773371985944205";
        if (jsonObject != null) {
//            uploadShippingInfo(mchId, outTradeNo, token, openid, desc, expressCompany, trackingNo);
        }
    }
    public static JSONObject queryWxExpress(String accessToken, String deliveryId, String waybillId) {
        String url = "https://api.weixin.qq.com/cgi-bin/express/business/path/get?access_token=" + accessToken;
        RestTemplate restTemplate = new RestTemplate();

        JSONObject req = new JSONObject();
        req.put("delivery_id", deliveryId);
        req.put("waybill_id", waybillId);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(req.toString(), headers);
        String result = restTemplate.postForObject(url, entity, String.class);
        return com.alibaba.fastjson2.JSONObject.parseObject(result);
    }



    public static void  uploadShippingInfo(String mchId, String outTradeNo, String accessToken, String openid, String desc, String expressCompany, String trackingNo) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" + accessToken;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);

        JSONObject orderKey = new JSONObject();
        // 订单单号类型，用于确认需要上传详情的订单。枚举值1，使用下单商户号和商户侧单号；枚举值2，使用微信支付单号。
        orderKey.put("order_number_type", 2);
        orderKey.put("mchid", mchId);
        orderKey.put("transaction_id",outTradeNo);
        // orderKey.put("out_trade_no", outTradeNo);

        JSONObject shippingList = new JSONObject();
        //商品信息
        shippingList.put("item_desc", desc);
        //物流单号，物流快递发货时必填
        shippingList.put("tracking_no", trackingNo);
        // 快递公司编码，物流快递发货时必填
        shippingList.put("express_company", expressCompany);

        JSONObject payer = new JSONObject();
        payer.put("openid", openid);

        JSONObject signObject = new JSONObject();
        JSONArray shipping_list = new JSONArray();
        shipping_list.add(shippingList);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String uploadTime = simpleDateFormat.format(System.currentTimeMillis());

        signObject.put("order_key", orderKey);
        // 发货模式，发货模式枚举值：1、UNIFIED_DELIVERY（统一发货）2、SPLIT_DELIVERY（分拆发货） 示例值: 1
        signObject.put("delivery_mode", 1);
        // 物流模式，发货方式枚举值：1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
        signObject.put("logistics_type", 1);
        signObject.put("shipping_list", shipping_list);
        signObject.put("upload_time", uploadTime);
        signObject.put("payer", payer);
        // log.info("发货信息：{}", signObject);

        // 构建包含请求体数据和请求头的HttpEntity对象
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(signObject, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        String body = responseEntity.getBody();
        System.out.println(body);
        System.out.println("11111111111");
        // JSONObject jsonObject = JSONUtil.parseObj(body);
        //String errcode = jsonObject.getString("errcode");
    }

    public static JSONObject searchWxID(String orderid ) throws Exception {
        String APIKEY = "10819801";
        String PRIVATE_KEY = "43173548";
        JSONObject params = new JSONObject();
        String   payParams =
                "nonceStr=effd910c69" +
                        "&outTradeNo=" +orderid+
                        "&terminalCode=" +APIKEY+
                        "&key="+PRIVATE_KEY;
        String sign = Md5Utils.toHex(Md5Utils.md5(payParams));
        params.put("outTradeNo", orderid);
        params.put("nonceStr", "effd910c69");
        params.put("terminalCode", APIKEY);
        params.put("sign", sign);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(params);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange("https://www.yqdfpay.com/api/third/v2.0/transaction/detail", HttpMethod.POST, requestEntity, String.class);
        String body = responseEntity.getBody();
        JSONObject object = JSONObject.parseObject(body);
        if("1".equals(object.getString("code"))){
            //无此交易
            return null;
        }else{
            System.out.println(object.getString("data"));
            JSONObject payinfo = JSONObject.parseObject(object.getString("data"));
            return  payinfo;
        }

    }

}
